/**
 * Http请求工具类
 * Created by yangyao on 2017/7/16.
 */
import Vue from 'vue'
import axios from 'axios'
// var JzHttp = axios.create({timeout: 1200})
if (process.env.NODE_ENV !== 'development') {
  axios.defaults.withCredentials = true
}
var JzHttp = axios.create()
JzHttp.interceptors.request.use(function (config) {
  if (config.url.slice(0, 8) === 'https://' || config.url.slice(0, 7) === 'http://') {
    config.url = config.url
  } else {
    config.url = config.baseURL + config.url
  }
  let httpBaseParamsCache = window.localStorage.getItem(httpBaseParamsCacheKey)
  if (httpBaseParamsCache !== null && httpBaseParamsCache !== '') {
    // 追加请求公共参数
    let httpBaseParams = JSON.parse(httpBaseParamsCache)
    // console.log('httpBaseParams', httpBaseParams)
    if (!config.params) {
      config.params = {}
    }
    for (let it in httpBaseParams) {
      config.params[it] = httpBaseParams[it]
    }
  }
  Vue.prototype.$tools.loading(true)
  return config
}, function (error) {
  console.log('请求发生异常', error)
  alert('请求发生异常', error)
  return Promise.reject(error)
})
// 这里应该统一封装 取值
JzHttp.interceptors.response.use(function (resp) {
  // console.log('请求结束，响应内容', resp)
  setTimeout(() => {
    Vue.prototype.$tools.loading(false)
  }, 500)
  return resp
}, function (error) {
  // alert(JSON.stringify(error))
  // console.log('请求返回异常，响应内容', error)
  return Promise.reject(error)
})

/**
 * 解析请求配置
 * @param configs
 */
function parseRequestConfigs (configs) {
  if (configs && configs !== null) {
    let reqInterceptor = configs.reqInterceptor
    let respInterceptor = configs.respInterceptor
    if (reqInterceptor) {
      JzHttp.interceptors.request.use(reqInterceptor.req, reqInterceptor.error)
    }
    if (respInterceptor) {
      JzHttp.interceptors.response.use(respInterceptor.resp, respInterceptor.error)
    }
    let headers = configs.headers
    if (headers) {
      for (let it in headers) {
        JzHttp.defaults.headers[it] = headers[it]
      }
    }
    let baseURL = configs.baseURL
    if (baseURL) {
      JzHttp.defaults.baseURL = baseURL
    }
  }
}

const httpBaseParamsCacheKey = 'httpBaseParams'

export default {
  /**
   * axios http请求对象
   */
  http: JzHttp,
  /**
   * 发起一个GET请求
   * @param url
   * @param params
   * @param config
   */
  get: function (url, params, configs) {
    if (!params) {
      params = {}
    }
    parseRequestConfigs(configs)
    return JzHttp.get(url, {
      params: params
    })
  },
  /**
   * 发起一个POST请求，发送JSON数据，Content-Type为application/json; charset=UTF-8
   * @param url
   * @param data
   * @param config
   */
  post: function (url, data, configs, vue) {
    if (!data) {
      data = {}
    }
    parseRequestConfigs(configs)
    return JzHttp
      .post(url, data, {})
  },
  /**
   * 发起一个POST表单请求，发送FORM表单数据
   * @param url
   * @param data
   * @param config
   */
  postForm: function (url, data, configs) {
    if (!data) {
      data = {}
    }
    parseRequestConfigs(configs)
    return JzHttp.post(url, data, {
      transformRequest: [function (data) {
        let form = ''
        for (let it in data) {
          let item = encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
          form += (item + '&')
        }
        if (form.indexOf('&') !== -1) {
          form = form.substring(0, form.length - 1)
        }
        return form
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  /**
   * 配置公共请求参数，发送http请求时会追加到url末尾作为url参数
   * @param key 参数key
   * @param value 参数value
   */
  pushBaseParam: function (key, value) {
    let httpBaseParamsCache = window.localStorage.getItem(httpBaseParamsCacheKey)
    let httpBaseParams
    if (httpBaseParamsCache === null || httpBaseParamsCache === '') {
      httpBaseParams = {}
    } else {
      httpBaseParams = JSON.parse(httpBaseParamsCache)
    }
    httpBaseParams[key] = value
    window.localStorage.setItem(httpBaseParamsCacheKey, JSON.stringify(httpBaseParams))
  }
}
